package gold.digger;

import java.util.Stack;

/**
 * Created by fanzhenyu02 on 2020/3/1.
 */
public class LC32 {

    public int longestValidParentheses(String s) {
        if (null == s || s.length() <= 1) {
            return 0;
        }

        Stack<Integer> st = new Stack();
        int length = 0;
        int start = 0;
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == '(') {
                st.push(i);
            } else if (st.size() <= 0) {
                start = i + 1;
            } else {
                st.pop();
                length = st.empty() ? Math.max(length, i + 1 - start) : Math.max(length, i - st.peek());
            }
        }

        return length;
    }


    public static void main(String[] args) {
        LC32 an = new LC32();

        String parentheses = ")()())";
        System.out.println(an.longestValidParentheses(parentheses));
    }
}
